package bjut.core.scanner;

import bjut.core.annotation.ZRpcScan;
import bjut.core.annotation.ZRpcService;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import java.util.Collections;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/7 13:57
 */
public class ZRpcScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
    // 注解里面的属性名
    private static final String BASE_PACKAGE_VALUE = "basePackage";
    private static final String ZRPC_BASE_PACKAGE = "bjut.core";


    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        //AnnotationAttributes  底层是LinkedHashMap
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(ZRpcScan.class.getName()));

        String[] scanBasePackages;

        if (annotationAttributes != null) {
            scanBasePackages = annotationAttributes.getStringArray(BASE_PACKAGE_VALUE);
        } else {
            // scanBasePackages = new String[]{ClassUtils.getPackageName(annotationMetadata.getClassName())};
            scanBasePackages = new String[]{((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName()};
        }

        ZRpcScanner zRpcScanner = new ZRpcScanner(beanDefinitionRegistry, ZRpcService.class);
        ZRpcScanner componentScanner = new ZRpcScanner(beanDefinitionRegistry, Component.class);

        if (resourceLoader != null) {
            zRpcScanner.setResourceLoader(resourceLoader);
            componentScanner.setResourceLoader(resourceLoader);
        }

        componentScanner.scan(ZRPC_BASE_PACKAGE);
        zRpcScanner.scan(scanBasePackages);

    }


}
